package TestPackage;

import com.sun.deploy.net.HttpUtils;
import net.sf.json.JSONObject;
import org.apache.commons.codec.digest.DigestUtils;
import redis.clients.jedis.Jedis;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.security.SecureRandom;
import java.util.Date;
import java.util.Random;

public class Test extends HttpServlet {
    public static final String SOURCES="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890";
    private Jedis jedis;
    public void init()throws ServletException {
              jedis=new Jedis("10.0.3.62",6379);
              jedis.auth("3698988plm");
              jedis.select(1);
    }

    public void doGet(HttpServletRequest req, HttpServletResponse resp)throws ServletException,IOException{
       System.out.println("doGet");
        System.out.println("检测redis数据库是否运行："+jedis.ping()+"\n"+jedis.get("js-api-ticket"));
    }

    public void doPost(HttpServletRequest req, HttpServletResponse resp)throws ServletException, IOException {

        req.setCharacterEncoding("UTF-8");
        resp.setCharacterEncoding("UTF-8");
        OutputStream outputStream=resp.getOutputStream();
        BufferedReader br=new BufferedReader(new InputStreamReader(req.getInputStream(),"UTF-8"));
        StringBuffer sb=new StringBuffer();
        String str=null;
        while((str=br.readLine())!=null){
          sb.append(str);
        }
        //System.out.println("接收的String："+sb);
        JSONObject json=JSONObject.fromObject(sb.toString());
        System.out.println("接收的JSON："+json.toString());
        long timestamp=new Date().getTime()/1000;
        String ticket=jedis.get("js-api-ticket");
        ticket=ticket.substring(1,ticket.length() - 1);
        String nonceStr =generateString(new SecureRandom(),SOURCES,16);
        String mw=String.format("jsapi_ticket=%s&noncestr=%s&timestamp=%s&url=%s",ticket,nonceStr,timestamp,json.getString("url"));
        System.out.println("明文:"+mw);
        mw= DigestUtils.sha1Hex(mw);
        System.out.println("密文："+mw);
        json=new JSONObject();
        json.put("nonce",nonceStr);
        json.put("time",timestamp);
        json.put("str",mw);
        outputStream.write(json.toString().getBytes("UTF-8"));
    }

    public String generateString(Random random , String characters, int length) {
        char[] text = new char[length];
        for (int i = 0; i < length; i++) {
            text[i] = characters.charAt(random.nextInt(characters.length()));
        }
        return new String(text);
    }
}
